package com.qf.routes;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerMain {
    public static void main(String[] args) throws IOException, TimeoutException {
        //①创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置rabbitmq所在机器ip
        factory.setHost("localhost");
        //设置rabbitmq所在机器的程序端口号
        factory.setPort(5672);
        //设置用户名
        factory.setUsername("guest");
        //设置密码
        factory.setPassword("guest");
        //设置虚拟主机
        factory.setVirtualHost("cdm1");

        //② 利用连接工厂创建连接对象
        Connection conn = factory.newConnection();
        //③ 基于connection获取对应的channel通道对象
        Channel channel = conn.createChannel();

        //④ 发布消息（发送到交换机，由交换机分发与之绑定的队列中）
        //DIRECT路由类型，会根据消息的路由键，将消息路由到指定的队列中
        channel.exchangeDeclare("routeEx",BuiltinExchangeType.DIRECT);

        channel.queueDeclare("routeQue1",true,false,false,null);
        channel.queueDeclare("routeQue2",true,false,false,null);

        //回头发送消息时，如果消息指定的路由键是A，那我这个消息就会发送到当前队列
        channel.queueBind("routeQue1","routeEx","A");
        //回头发送消息时，如果消息指定的路由键是B，那我这个消息就会发送到当前队列
        channel.queueBind("routeQue2","routeEx","B");

        channel.basicPublish("routeEx","A",null,"路由消息-键A 11".getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("routeEx","A",null,"路由消息-键A 22".getBytes(StandardCharsets.UTF_8));

        channel.basicPublish("routeEx","B",null,"路由消息-键B 11".getBytes(StandardCharsets.UTF_8));

        //⑤ 释放资源
        channel.close();
        conn.close();
    }
}
